﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
//
using Model;
using BLL;

namespace T03.Controllers
{
    public class UsersController : Controller
    {
        //
        // GET: /Users/
        UsersBLL bll = new UsersBLL();
        // GET: /Users/Index
        public ActionResult Index(int? id = null)
        {
            if (id != null)

                return View(bll.GetUserByID(id));
            else
                return View(bll.GetAll());
        }

        // GET: /Users/MyArticles
        public ActionResult MyArticles()
        {
            int uid= 1;
            ViewBag.Articles = bll.GetArticlesByID(uid);
            return View();
        }


        // GET: /Users/Register 登录
        public ActionResult Login()
        {
            return View();
        }
        // GET: /Users/Register 登录,处理post请求
        [HttpPost]
        public ActionResult Login(string uname, string pwd)
        {
            //uname为在页面定义的name="uname"控件的值
            Users loginuser = bll.Login(uname, pwd);
            if (loginuser != null)
            {
                Session["login"] = loginuser;//在session中保存登录用户对象
                return RedirectToAction("Index", "Home"); //跳转到主页(不同控制器)
            }
            else
            {
                //在TempData中保存登录信息,也可用于传递注册成功后提示信息!
                TempData["msg"] = "帐号或密码错误";
            }
            return View();
        }

        // GET: /Users/Register 注册
        public ActionResult Register()
        {
            return View();
        }
        // GET: /Users/Register 注册,处理post请求
        [HttpPost]
        public ActionResult Register(Users u)
        {
            if (bll.Add(u))
            {
                TempData["msg"] = "新增成功,请输入昵称密码进行登录!";
                return RedirectToAction("Login");//跳转到登录(相同控制器)
            }
            return View();
        }

        // GET: /Users/UpdatePwd 修改密码
        public ActionResult UpdatePwd()
        {
            return View();
        }
        // GET: /Users/UpdatePwd 注册,处理post请求
        [HttpPost]
        public ActionResult UpdatePwd(string oldpwd,string newpwd)
        {
            Users login=(Users)Session["login"];
            if (oldpwd != login.UserPass)
            {
                TempData["msg"] = "原密码错误!!";
            }
            else
            {
                login.UserPass = newpwd;
                if (bll.UpdatePwd(login))
                {
                    TempData["msg"] = "修改密码成功,请重新登录!";
                    return RedirectToAction("Login");//跳转到登录(相同控制器)
                }
                else
                {
                    TempData["msg"] = "修改密码失败!";
                }
            }
            return View();
        }


    }
}
